#include <REGX52.H>

sbit Key1 = P3^1;
sbit Key2 = P3^0;
sbit Key3 = P3^2;
sbit Key4 = P3^3;

sbit LED1 = P2^0;
sbit LED2 = P2^1;
sbit LED3 = P2^2;
sbit LED4 = P2^3;
sbit LED5 = P2^4;
sbit LED6 = P2^5;
sbit LED7 = P2^6;
sbit LED8 = P2^7;

extern void clear();

// 设置全局变量Key_Status用来存储Key的状态
unsigned char Key_Status[4] = {1,1,1,1};

void KeyCheck(){
	// 起始未按下 用于存储按键状态的变量keybuf 最开始置全1
	static unsigned char keybuf[4] = {0xFF,0xFF,0xFF,0xFF};
	int i = 0;
	// 每次将新检测到的Key1状态存储到最低位
	keybuf[0] = (keybuf[0] << 1) | Key1;
	keybuf[1] = (keybuf[1] << 1) | Key2;
	keybuf[2] = (keybuf[2] << 1) | Key3;
	keybuf[3] = (keybuf[3] << 1) | Key4;
	for( i = 0 ; i < 4; i++){
		// 当keybuf为全0时，可得按键被按下
		if(keybuf[i] == 0x00){
			// 检测之前是否为高电平
			if(Key_Status[i]){
				switch(i){
					// 当 Key1 被按下时
					case 0:
						LED1 = ~LED1;
						LED8 = ~LED8;
						TR1 = ~TR1;
					break;	
					// 当 Key2 被按下时
					case 1:
						LED2 = ~LED2;
						LED7 = ~LED7;
					if(!TR1){
						clear();
						Stopwatch_ShowTime();
					}
					break;
					// 当 Key3 被按下时
					case 2:
						LED3 = ~LED3;
						LED6 = ~LED6;
					break;
					// 当 Key4 被按下时
					case 3:
						LED4 = ~LED4;
						LED5 = ~LED5;
					break;
				}
			}
			// 并将按键引脚状态设置为0
			Key_Status[i] = 0;
		}
		
		// 当keybuf为全1时，可得此时已经松手
		if(keybuf[i] == 0xFF){
			// 则将按键引脚状态设置为1
			Key_Status[i] = 1;
		}
	}
}
